﻿using System;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Atmk.WaterMeter.MIS.Commons.Interfaces.WeiXin;
using Atmk.WaterMeter.MIS.Commons.Utils;
using Atmk.WaterMeter.MIS.Commons.ViewModels.WeiXin;
using Atmk.WaterMeter.MIS.Pay.WeiXin.Lib;
using NLog;
using RestSharp;

namespace Atmk.WaterMeter.MIS.Pay.WeiXin.Logic
{
    /// <summary>
    /// 微信付款商户服务逻辑
    /// </summary>
    public class WxPaymentLogic:IWxPayment
    {
        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 小程序的统一订单
        /// </summary>
        /// <param name="appid">小程序id</param>
        /// <param name="openId">用户id</param>
        /// <param name="mch_id">商户id</param>
        /// <param name="callBackUrl">回调地址</param>
        /// <param name="mis_key">商户key</param>
        /// <param name="total_fee">充值金额(分)</param>
        /// <returns></returns>
        public async Task<ResponUnifiedorder> SmallRoutineUnifiedorder(string appid, string openId,
            string mch_id, string callBackUrl, string mis_key, int total_fee)
        {
            var config = WxPayConfig(appid, openId, mch_id, callBackUrl, mis_key);
            var requestData = WxPayDataUnifiedorder(config, total_fee);
            //下单方法
            var request = new RestRequest(Method.POST);
            var x = requestData.ToXml();
            request.RequestFormat = DataFormat.Xml;
            request.AddParameter("text/xml", x, ParameterType.RequestBody);
            var _client =
                new RestClient(WxUrlManage.Urlunifiedorder)
                {
                    RemoteCertificateValidationCallback = ValidateServerCertificate
                };
            var response = await _client.ExecuteTaskAsync(request);
            //将响应订单转为WxPayData
            var responseData = new WxPayData();
            Console.WriteLine(response.Content);
            try
            {
                responseData.FromXml(response.Content,config.MisKey);
                if (responseData.GetValue("return_code").ToString() == "FAIL")
                {
                    var r = new ResponUnifiedorder
                    {
                        err_code = "RETURN_ERROR",
                        err_code_des = responseData.GetValue("return_msg").ToString()
                    };
                    return r;
                }
                try
                {
                    //响应值WxPayData转为抄表系统微信订单反馈对象
                    var r = responseData.ToResponUnifiedorder();
                    r.out_trade_no = requestData.GetValue("out_trade_no").ToString();
                    return r;
                }
                catch (WxPayException e)
                {
                    var r = new ResponUnifiedorder
                    {
                        err_code = "RETURN_ERROR",
                        err_code_des = e.Message
                    };
                    return r;
                }
            }
            catch (WxPayException e)
            {
                var r = new ResponUnifiedorder
                {
                    err_code = "RETURN_ERROR",
                    err_code_des = e.Message
                };
                return r;
            }

        }

        private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors)
        {
            return true;
        }

        /// <summary>
        /// 统一订单赋值
        /// </summary>
        /// <param name="wxPayConfig"></param>
        /// <param name="total_fee"></param>
        /// <returns></returns>
        private static WxPayData WxPayDataUnifiedorder(WxPayConfig wxPayConfig,int total_fee)
        {
            //统一下单预赋值
            var data = new WxPayData();
            data.SetValue("body", "奥特美克自来水费用管理助手-用户充值缴费");
            data.SetValue("attach", "test");
            data.SetValue("out_trade_no", WxPayDataAssignment.GenerateOutTradeNo(wxPayConfig.MchId));
            data.SetValue("total_fee", total_fee);
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss")); //有效期10分钟
            data.SetValue("goods_tag", "test");
            data.SetValue("trade_type", "JSAPI");
            data.SetValue("openid", wxPayConfig.OpenId);
            //统一下单表单处理
            var result = WxPayDataAssignment.OutUnifiedOrder(data, wxPayConfig);
            return result;
        }
        /// <summary>
        /// 获取配置
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="openId"></param>
        /// <param name="mch_id"></param>
        /// <param name="callBackUrl"></param>
        /// <param name="mis_key"></param>
        /// <returns></returns>
        private static WxPayConfig WxPayConfig(string appid, string openId, string mch_id, string callBackUrl, string mis_key)
        {
            var ip = Simple.GetLocalIP();
            if (ip == "")
                ip = "127.0.0.1";
            var config = new WxPayConfig(appid, openId, mch_id, callBackUrl, mis_key, ip);
            return config;
        }
    }
}
